var fs = require('fs');
var xlsx = require('node-xlsx');
var express = require('express');
var ajax = require('./ajax.js');
const app = express()
const server = require('http').Server(app)


const DEFAULT_PORT = 80
const startSignDate = "2021-12-20"
const endSignDate = "2021-12-21"
const map = [
    { id:'81868233.zh',idCode:'Zts+PfQo6gH9HNe/4Ez3DA==' },
    { id:'98805112.zh',idCode:'KBRjtGgufSv0ndkuz8Y72Q==' },
    { id:'20313396.zh',idCode:'j6NwsejeVUltfS414Qy97w==' },
    { id:'25609315',idCode:'kBnst9wH9oa8ImfAGsSzjg==' },
    { id:'91936959',idCode:'ILRCjBr8Tv3je0/kYXgf/A==' },
    { id:'12526965',idCode:'CGF9y8eoA337jRVS5CDi+g==' },
    { id:'58838892.zh',idCode:'J/mYXONh6rYrSvhHr1B3kQ==' },
    { id:'65280982.zh',idCode:'f73qhSaQnbr5gnHNZZsazQ==' },
    { id:'12602799',idCode:'+RBZoDpdeXY8IkyuyONWLA==' },
    { id:'67579070.zh',idCode:'R9ZRva7El26W36EhJPexdg==' },
    { id:'62237613',idCode:'bCkyS/BqzM63CeLAi//zEQ==' },
    { id:'68970518',idCode:'Si5h++MIx4D30yRR03YCWQ==' },
    { id:'77091351.zh',idCode:'I2yj8SJ/ZgJVbQq1BR/ddg==' },
    { id:'00666221',idCode:'UJC9ozCn0rKFWk4+RYUmOg==' },
    { id:'33583668.zh',idCode:'ZFdPQT7+nl3Ze96mUAPMSg==' },
    { id:'87966291',idCode:'A8sgNyo2c+SluxlImdvg8w==' },
    { id:'58131368.zh',idCode:'+8DTPWq0yQRUQgv81R4sfw==' },
    { id:'63125718',idCode:' pArP2yZ0uaeQGOPshvBIvg==' },
    { id:'31960116',idCode:'7fMjArDV6c5p4uY+9EnFEg==' },
    { id:'63832373.zh',idCode:'28zzCCa/yhxCxygHPG21Yg==' },
    { id:'50053217',idCode:'apIHQkfq8+j05BSJiMmmMw==' },
    { id:'20955156.zh',idCode:'oiMnMinl6Tk028Pd61pdXg==' },
    { id:'03706680',idCode:'A36IsGO5dv488L7kflqBWw==' },
    { id:'90350595',idCode:'OjFRWZFVaWtOqmj5Nsr1Pw==' },
    { id:'58507298',idCode:'SWRKTECsFoSH7Qo7Cz2SWA==' },
    { id:'93607729',idCode:'zUnciomF55ZtAmk8ierlAg==' },
    { id:'57056257',idCode:'nqND1NTbU7biuPnX08BY2Q==' },
    { id:'20569022',idCode:'M+bzOAi9iem6ygj68TRO3A==' },
    { id:'23010891',idCode:'IWDT0AWsV8geADxSNqmx3A==' },
    { id:'06530691',idCode:'v9zzXs8EguB2IwgCWIfGkA==' },
];
var tableDatas = [], PromiseArr = [];


const CryptoJS = require('crypto-js')
const key = CryptoJS.enc.Utf8.parse("ccbnwams182jiami")
const iv = CryptoJS.enc.Utf8.parse("ccbnwams182jiami")
function Encrypt(word){
    let srcs = CryptoJS.enc.Utf8.parse(word)
    let encrypted = CryptoJS.AES.encrypt(srcs, key, {iv, mode: CryptoJS.mode.CBC, padding:CryptoJS.pad.pk})
    return encrypted.ciphertext.toString().toUpperCase();
}
console.log( Encrypt('58131368') )
// function aesEncrypt(data, key){
//     const cipher = crypto.createCipher('aes192', key);
//     var crypted = cipher.update(data, 'utf8', 'base64');
//     crypted += cipher.final('base64');
//     return crypted
// }
// console.log(CryptoJS.enc)
// console.log(aesEncrypt("58131368", "ccbnwams182jiami"))
// console.log(crypto)
// crypto.publicEncrypt.Utf8.parse("ccbnwams182jiami")
// const hash = crypto.createHash('md5')
// var a = hash.update('58131368').digest('base64')
// console.log(a, a.length)
// for (let index = 0; index < map.length; index++) {
//     PromiseArr.push( ajaxLogin(map[index], index) );
// }
// Promise.all(PromiseArr).then(()=>{
//     tableDatas = bubbleSort(tableDatas)
//     // getHTML()
//     getXls()
// })



function bubbleSort(arr){
    for (var i = 0; i < arr.length-1; i++) {
        for (let j = 0; j < arr.length-i-1; j++) {
            if(arr[j].index>arr[j+1].index){
                var temp = arr[j]
                arr[j] = arr[j+1]
                arr[j+1] = temp
            }
        }
    }
    return arr
}
function ajaxLogin(element, index){
    return new Promise((resolve,reject)=>{
        ajax.ajax({
            url: "http://11.36.199.84:8000/wams-manager/login",
            type: "POST",
            data: {
                personLogin: element.id,
                personPass: "uiNr6eA0KZm/I8VnQiTPtA=="
            },
            success: function (res) {
                //res.data[1].cardId
                try {
                    ajaxData(element.idCode,res.data[1].personId,res.data[2].accessToken, index, resolve);
                } catch (error) {
                    console.log("!!!!!!!!!!!!!ajaxLoginError!!!!!!!!!!!!!："+error)
                    tableDatas = [...tableDatas, {index}];
                    resolve()
                }
            },
            error: function (e) {
                console.log("!!!!!!!!!!!!!error!!!!!!!!!!!!!："+e)
                resolve()
            }
        });
    })
}
function ajaxData(cardId,personId,accessToken, index, callback){
    if(cardId&&personId&&accessToken){
        ajax.ajax({
            url: "http://11.36.199.84:8000/wams-manager/AttendanceManager/playCardOwner",
            type: "POST",
            data: {
                endSignDate,
                pageNumber: 1,
                pageSize: 10,
                personId,
                proBaseId: "",
                startSignDate,
            },
            headers:{
                accessToken,cardId
            },
            success: function (res) {
                if(res.data && res.data.records){
                    res.data.records = res.data.records.map(v=>({...v, index}))
                    tableDatas = [...tableDatas, ...res.data.records];
                }else{
                    tableDatas = [...tableDatas, {index}];
                }
                callback(1)
            },
            error: function (e) {
                console.log("!!!!!!!!!!!!!error!!!!!!!!!!!!!："+e)
                callback(2)
            }
        })
    }else{
        tableDatas = [...tableDatas, {index}];
        callback(1)
    }
}
function getHTML(){
    var tr = ""
    var RED = `style="color:red;font-weight:bold;text-align: right;"`
    for (let i = 0; i < tableDatas.length; i++) {
        const e = tableDatas[i];
        tr+=`<tr>
            <td>${e.index*1+1}</td>
            <td>${e.personName}</td>
            <td>${e.signDate}</td>
            <td>${e.signIn}</td>
            <td ${(e.signOut&&((e.signOut).substr(11,2)>"20"))?RED:''}>${e.signOut}</td>
            <td ${e.workTimes<"480"?RED:''}>${e.workTimes}</td>
        </tr>`;
    }
    app.use(function (req, res, next) {  
        res.write(`<!DOCTYPE html>
        <html lang="en">
            <head>
                <meta charset="utf-8">
                <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
                <meta name="theme-color" content="#000000">
                <title></title>
                <style>
                    table{border-collapse:collapse;}
                    table,td,th{border:1px solid black;padding: 5px 10px;text-align: center;}
                </style>
            </head>
            <body>
                <div id="root">
                <table>
                    <thead>
                        <tr>
                            <th>序号</th>
                            <th>姓名</th>
                            <th>日期</th>
                            <th>签到时间</th>
                            <th>签退时间</th>
                            <th>工作时长(分钟)</th>
                        </tr>
                    </thead>
                    <tbody>${tr}
                    </tbody>
                </table>
                </div>
            </body>
        </html>`)
            res.end()
    })
    server.listen(DEFAULT_PORT, function () {
        console.log('node app start at port '+DEFAULT_PORT)
    })
}
function getXls() {
    var buffer = xlsx.build([
        {"name": "考勤明细", "data": [
            ['序号','姓名','日期','签到时间','签退时间','工作时长(分钟)'],
            ...tableDatas.map(v=>[v.index*1+1, v.personName, v.signDate, v.signIn, v.signOut, v.workTimes, ])
        ]}
    ]);
    fs.writeFileSync(`${startSignDate}至${endSignDate}.xlsx`, buffer);
}

